package com.java.reflect;

import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class Reflect05_User {
    public static void main(String[] args) throws Exception {
        Class userClass = User.class ;
        // 获取所有公共方法[包括父类和Object类方法]
        Method[] pubMethods = userClass.getMethods() ;
        printMethod(pubMethods);
        // 获取全部方法
        Method[] allMethods = userClass.getDeclaredMethods() ;
        printMethod(allMethods);
        // 获取指定方法
        Method method = userClass.getMethod("parName",String.class) ;
        printMethod(new Method[]{method});
        // 调用方法
        Object userObj = userClass.newInstance() ;
        Method setId = userClass.getDeclaredMethod("setId", Integer.class);
        setId.invoke(userObj,99) ;
        Method setName = userClass.getDeclaredMethod("setName", String.class);
        setName.invoke(userObj,"java") ;
        Method sayHi = userClass.getDeclaredMethod("sayHi", String.class);
        sayHi.setAccessible(Boolean.TRUE);
        sayHi.invoke(userObj,"c++");
        System.out.println(userObj);
    }
    /**
     * 打印方法信息
     */
    public static void printMethod (Method[] methods){
        for (Method method : methods){
            System.out.println("定义："+method);
            System.out.println("命名："+method.getName());
            UserAnno userAnno = method.getAnnotation(UserAnno.class) ;
            if (userAnno != null){
                System.out.println("注解："+userAnno.desc());
            }
            Type[] paramTypeArr = method.getParameterTypes();
            for (int i=0 ; i< paramTypeArr.length; i++){
                System.out.print("参数"+(i+1)+"类型："+paramTypeArr[i]+" ; ");
            }
            System.out.println("参数个数："+method.getParameterCount());
            System.out.println("================================");
        }
    }
}
